package UDP.chat.improve;

import java.net.DatagramPacket;
import java.net.DatagramSocket;

//接收消息
public class thread_receive extends Thread {
    private DatagramSocket socket = null;//udp套接字
    private DatagramPacket packet = null;//包
    private int port;//端口
    private static Boolean bj = true;

    /**
     * 构造方法
     */
    public thread_receive() {
    }

    public thread_receive(int port) {
        this.port = port;
    }

    @Override
    public void run() {
        try {
            //1.指点端口
            socket = new DatagramSocket(port);
            while (bj) {
                //2.1创建接收空间
                byte[] bytes = new byte[1024];
                //2.2创建接收包
                packet = new DatagramPacket(bytes, 0, bytes.length);
                //3接收包
                socket.receive(packet);

                //4.打印消息
                String s = new String(packet.getData(), 0, packet.getLength());//才分包中的数据
                System.out.println(s);

                //5.判断标志位
                if (s.matches(".*bye.*")) {
                    bj = false;
                    System.out.println("接收消息进程关闭");
                    socket.close();
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }finally {

        }
    }
}
